package com.blue.bluecode.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * BitmapUtil Bitmap的帮助类
 * Created by bluewaitor on 2015/4/13.
 */
public class BitmapUtil {

    /**
     * 获取inSampleSize的值,inSampleSize如果是2,则将Bitmap缩放1/2
     * @param options BitmapFactory.Options
     * @param targetWidth 目标宽
     * @param targetHeight 目标高
     * @return 返回inSampleSize
     */
    public static int getInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight){
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if(width > targetWidth || height > targetHeight){
            final int halfWidth = width/2;
            final int halfHeight = height/2;
            while((halfWidth / inSampleSize) > targetWidth && (halfHeight / inSampleSize) > targetHeight ){
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 获取指定宽高的的Bitmap
     * @param res Resources
     * @param resId resId
     * @param targetWidth 目标宽
     * @param targetHeight 目标高
     * @return Bitmap
     */
    public static Bitmap decodeSuitableBitmapFromResource(Resources res, int resId, int targetWidth, int targetHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res,resId,options);
        options.inSampleSize = getInSampleSize(options,targetWidth,targetHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

}
